package com.it.gmall.order.controller;

import com.it.gmall.common.constant.RedisConst;
import com.it.gmall.common.result.Result;
import com.it.gmall.model.cart.CartInfo;
import com.it.gmall.model.order.OrderDetail;
import com.it.gmall.model.order.OrderInfo;
import com.it.gmall.order.service.OrderApiService;
import com.it.gmall.order.service.OrderApiServiceAsync;
import com.it.gmall.user.client.UserFeignClient;
import com.it.gmall.cart.client.CartFeignClient;
import com.it.gmall.model.user.UserAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("api/order")
public class OrderApiController {
    @Autowired
    private CartFeignClient cartFeignClient;
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrderApiService orderApiService;

    // 去结算页面
    @GetMapping("/trade")
    public Map trade(HttpServletRequest request){
        Map map = new HashMap<>();

        // 获取用户id
        String userId = request.getHeader("userId");

        // 返回用户地址
        List<UserAddress> userAddressList = userFeignClient.getUserAddress();
        System.out.println(userAddressList);
        map.put("userAddressList",userAddressList);

        // 返回选中的购物车商品清单
        List<CartInfo> cartInfoList = cartFeignClient.getCheckedCartInfo();
        List<OrderDetail> detailArrayList = cartInfoList.stream().map((cartInfo)->{
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setSkuId(cartInfo.getSkuId()); // sku_id
            orderDetail.setSkuName(cartInfo.getSkuName()); // sku_name
            orderDetail.setImgUrl(cartInfo.getImgUrl()); // 图片名称
            orderDetail.setOrderPrice(cartInfo.getSkuPrice()); // 实时价格（购买时的价格）
            orderDetail.setSkuNum(cartInfo.getSkuNum()); // 购买数量
            return orderDetail;
        }).collect(Collectors.toList());
        map.put("detailArrayList",detailArrayList);

        // 小计 总数量和总价格
        // 1.1 总数量
        long sum = detailArrayList.stream().collect(Collectors.summarizingInt(OrderDetail::getSkuNum)).getSum();
        map.put("totalNum",sum);
        // 1.2 总价格 总价格 = 总价格 + (数量*单价)
        // 总价格初始值
        BigDecimal totalPrice = new BigDecimal("0");
        for (OrderDetail orderDetail : detailArrayList) {
            // 每一个商品的 价格*数量
            BigDecimal multiplyPrice
                    = orderDetail.getOrderPrice().multiply(new BigDecimal(orderDetail.getSkuNum()));
            // 计算总价
            totalPrice = totalPrice.add(multiplyPrice);
        }
        map.put("totalAmount",totalPrice);
        // 1.3 计算总价的另一种方式
        /*BigDecimal totalPrice = detailArrayList.stream().map(orderDetail ->
                orderDetail.getOrderPrice().multiply(new BigDecimal(orderDetail.getSkuNum()))
        ).reduce(BigDecimal.ZERO, BigDecimal::add);*/

        // 订单号/交易号 防止二次提交 幂等性问题
        String uuid = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set("tradeNo:"+userId,uuid);
        map.put("tradeNo",uuid);

        return map;
    }

    // 提交订单
    // /auth/submitOrder?tradeNo=' + tradeNo
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo,String tradeNo,HttpServletRequest request){
        String userId = request.getHeader("userId");
        // 1.校验交易号是否正确
        if(StringUtils.isEmpty(tradeNo)){
            return Result.fail().message("订单不存在");
        }else{
            Object tradeNoRedis = redisTemplate.opsForValue().get("tradeNo:" + userId);
            if(StringUtils.isEmpty(tradeNoRedis)){
                return Result.fail().message("不能重复提交订单");
            }else{
                if (!tradeNo.equals(tradeNoRedis)) {
                    return Result.fail().message("订单号有误");
                }
            }
        }
        // 从缓存中删除订单
        redisTemplate.delete("tradeNo:"+tradeNo);

        // 2.校验库存
        // 获取订单数据商品列表
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        for (OrderDetail orderDetail : orderDetailList) {
            Boolean isHave = orderApiService.isHaveStock(orderDetail);
            if(isHave){ //没有库存
                return Result.fail().message(orderDetail.getSkuName()+"库存不足!");
            }
        }

        // 3.提交订单
        // 设置用户id到订单信息中
        orderInfo.setUserId(Long.parseLong(userId));
        long orderId = orderApiService.subOrder(orderInfo);

        // 返回订单id
        return Result.ok(orderId);
    }

    // 根据订单id查询订单信息
    @GetMapping("/auth/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable Long orderId){
        return orderApiService.getOrderInfo(orderId);
    }

    // 拆单
    //  [{"wareId":"1","skuIds":["2","10"]},{"wareId":"2","skuIds":["3"]}]
    @PostMapping("/orderSplit")
    public List<Map> splitWareOrder(HttpServletRequest request){
        String wareSkuMap = request.getParameter("wareSkuMap");
        String orderId = request.getParameter("orderId"); // 订单id
        List<OrderInfo> splitOrder = orderApiService.splitOrder(Long.parseLong(orderId),wareSkuMap);
        List<Map> mapList = orderApiService.initWareInfo(splitOrder);
        return mapList;
    }
}
